package com.xd.common.util;

import com.google.common.collect.Maps;
import com.itextpdf.text.Document;
import com.itextpdf.text.pdf.AcroFields;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfStamper;

import java.io.*;
import java.util.Iterator;
import java.util.Map;

public class PdfUtil {
    /**
     * @param map          写入的数据
     * @param templatePath pdf模板路径
     */
    // 利用模板生成pdf
    public static void Pdf(Map<String, Object> map, String templatePath, AaLiOss aaLiOss, String alyUrl) {
        ByteArrayOutputStream bos = null;
        PdfReader reader = null;
        PdfStamper stamper = null;
        Document doc = null;
        try {
            reader = new PdfReader(templatePath);// 读取pdf模板
            bos = new ByteArrayOutputStream();
            stamper = new PdfStamper(reader, bos);
            AcroFields form = stamper.getAcroFields();
            // 设置字体，否则可能会不显示中文
            BaseFont bf = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
            form.addSubstitutionFont(bf);
            Iterator<String> it = form.getFields().keySet().iterator();
            while (it.hasNext()) {
                String name = it.next().toString();
                String value = map.get(name) != null ? map.get(name).toString() : null;
                form.setField(name, value);
            }
            stamper.setFormFlattening(true);// 如果为false那么生成的PDF文件还能编辑，一定要设为true
            doc = new Document();
            doc.open();
            stamper.close();
            doc.close();
            reader.close();
            aaLiOss.upload(alyUrl, new ByteArrayInputStream(bos.toByteArray()));
        } catch (Exception e) {
            System.out.println("===============PDF导出失败=============");
            e.printStackTrace();
        } finally {
            try {
                if (doc != null)
                    doc.close();
                if (reader != null)
                    reader.close();
                if (stamper != null)
                    stamper.close();
                if (bos != null)
                    bos.close();
            } catch (Exception e) {
                System.out.println("===============PDF流关闭失败=============");
                e.printStackTrace();
            }
        }
    }
    /*
    * inputPath:下载到服务器地址
    * templatePath:模板地址
    * map:参数
    * */
    public static void Pdf2(Map<String, Object> map, String templatePath,String inputPath) {
        ByteArrayOutputStream bos = null;
        PdfReader reader = null;
        PdfStamper stamper = null;
        Document doc = null;
        File dirFile = new File(inputPath.substring(0,inputPath.lastIndexOf("/")));
        if (!dirFile.exists()) {
            dirFile.mkdirs();
        }

        try {
            reader = new PdfReader(templatePath);// 读取pdf模板
            bos = new ByteArrayOutputStream();
            stamper = new PdfStamper(reader, bos);
            AcroFields form = stamper.getAcroFields();
            // 设置字体，否则可能会不显示中文
            BaseFont bf = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
            form.addSubstitutionFont(bf);
            Iterator<String> it = form.getFields().keySet().iterator();
            while (it.hasNext()) {
                String name = it.next().toString();
                String value = map.get(name) != null ? map.get(name).toString() : null;
                form.setField(name, value);
                if (name.equals("gou")){
                    form.setField(name, "false",true);
                }
            }
            stamper.setFormFlattening(true);// 如果为false那么生成的PDF文件还能编辑，一定要设为true
            doc = new Document();
            doc.open();
            stamper.close();
            doc.close();
            reader.close();

            FileOutputStream outputStream = null;
            outputStream = new FileOutputStream(inputPath);
            outputStream.write(bos.toByteArray());
            outputStream.flush();

//            aaLiOss.upload(alyUrl, new ByteArrayInputStream(bos.toByteArray()));
        } catch (Exception e) {
            System.out.println("===============PDF导出失败=============");
            e.printStackTrace();
        } finally {
            try {
                if (doc != null)
                    doc.close();
                if (reader != null)
                    reader.close();
                if (stamper != null)
                    stamper.close();
                if (bos != null)
                    bos.close();
            } catch (Exception e) {
                System.out.println("===============PDF流关闭失败=============");
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) throws FileNotFoundException {
        Map<String, Object> map = Maps.newHashMap();
        map.put("name", "旭哥哥.迈克尔.杰克逊");
        map.put("time", "2024年03月13日 00:00:00");
        map.put("idcard", "511621199508260337");
//        Pdf2(map,  "/个人信息授权使用书模板.pdf");
    }

}

